<script setup>
import {onMounted, ref} from 'vue';
import luckysheet from "luckysheet";
import AnalyesAPI from "@/api/system/analyes.ts";
import {useAnalysetStore} from "@/store/index.ts";
import {
  filterParallelSamples,
  filterValidSampleAdatas,
  filterValidSamples, jbylSamples,
  kbylSamples,
  processTableData,
  qxylSamples, zkylSamples
} from '@/utils/method'
import FluorideB from "@/components/analysisSheetComponents/waterCapacity/tmpl57/index.vue";
import {transformData} from "@/utils/method";
import Index from '@/components/analysisSheetComponents/component/index.vue';
import Device from "@/components/analysisSheetComponents/component/Device.vue";

let options = {
  container: "luckysheet", //luckysheet为容器id
  lang: 'zh',
  autoCalculate: true,
  data: [
    {
      "column": 7, // 列数
      "defaultRowHeight": 40, // 自定义行高
      "defaultColWidth": 100, // 自定义列宽
      "celldata": [
        // 初始化表格数据，第一行包含表头
        {"r": 0, "c": 0, "v": "样品编号",}, // A1
        {"r": 0, "c": 1, "v": "类型",}, // A1
        {"r": 0, "c": 2, "v": "分取试样体积V（mL）",}, // B1
        {"r": 0, "c": 3, "v": "分取后定容体积V1（mL）",}, // C1
        {"r": 0, "c": 4, "v": "机读浓度ρ1(μg/L)",}, // D1
        {"r": 0, "c": 5, "v": "稀释倍数f",}, // E1
        {"r": 0, "c": 6, "v": "样品浓度ρ(μg/L)",}, // C1
        {"r": 0, "c": 7, "v": "测定结果(μg/L)",}, // C1
        {"r": 0, "c": 8, "v": "备注",}, // D1
      ], // 初始化数据
      "config": {
        "columnlen": { // 设置列宽
          "0": 200,
          "1": 150,
          "2": 150,
          "3": 150,
          "4": 150,
          "5": 150,
          "6": 150,
        }, // 表格列宽
      },
    }
  ],
  showinfobar: false, // 隐藏信息栏
  showtoolbar: true, // 隐藏工具栏
};

const sheetData = ref('')
const waterForm = ref({
  bdatas: {
    qxhzdatas: {},
    qxjhdcd: [
      {ypbh: '', xdwc: '', zkyq: '', sfhg: ''},
      {ypbh: '', xdwc: '', zkyq: '', sfhg: ''},
    ],
  },
  pxycd: Array.from({length: 12}, () => ({
    px_ypbh: "", px_cdnd: "", px_pjz: "", px_xdpc: "", px_zkyq: "", px_sfhg: ""
  })),
  kbycd: [
    {kb_ypbh: '', kb_cdnd: '', kb_zkyq: '', kb_sfhg: ''},
    {kb_ypbh: '', kb_cdnd: '', kb_zkyq: '', kb_sfhg: ''},
    {kb_ypbh: '', kb_cdnd: '', kb_zkyq: '', kb_sfhg: ''},
    {kb_ypbh: '', kb_cdnd: '', kb_zkyq: '', kb_sfhg: ''},
  ],
  bzycd: [
    {bz_ypbh: '', bz_cdnd: '', bz_bzz: '', bz_sfhg: ''},
    {bz_ypbh: '', bz_cdnd: '', bz_bzz: '', bz_sfhg: ''},
  ],
  jbycd: [
    {jb_ypbh: '', jb_bynd: '', jb_jbl: '', jb_yypnd: '', jb_jbhnd: '', jb_jbhsl: '', jb_zkyq: '', jb_sfhg: ''},
    {jb_ypbh: '', jb_bynd: '', jb_jbl: '', jb_yypnd: '', jb_jbhnd: '', jb_jbhsl: '', jb_zkyq: '', jb_sfhg: ''},
    {jb_ypbh: '', jb_bynd: '', jb_jbl: '', jb_yypnd: '', jb_jbhnd: '', jb_jbhsl: '', jb_zkyq: '', jb_sfhg: ''},
  ],
  unit: {},
  device: {
    device_name: [],
    device_model: [],
    device_number: [],
  },
})
const listB = ref({
  kbyList: [],
  qxyList: [],
  pxyList: [],
  bzyList: [],
})
const cdatas = ref([])
const analyseStatusPage = useAnalysetStore()
const record_sn = analyseStatusPage.waterForm.record_sn
const processedData = ref([])
const switchAB = ref(true)
const switchAdd = ref(true)
// 在组件挂载后初始化 Lucky-sheet
onMounted(() => {
  // 初始化表格
  luckysheet.create(options);
  // 获取表单信息
  getWaterCapacity()
  getMethod()
});


// 获取信息(也要粘贴)
const getMethod = () => {
  waterForm.value.task_name = analyseStatusPage.waterForm.task_number //任务名称
  waterForm.value.method = analyseStatusPage.waterForm.tableItem.test_method
      ? analyseStatusPage.waterForm.tableItem.test_method
      : analyseStatusPage.waterForm.tableItem.test_method_number;//分析方法
  waterForm.value.category_id = analyseStatusPage.waterForm.tableItem.sample_category // 样品类别
}

// 获取工作表信息
const getWaterCapacity = () => {
  let josn = {
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    task_id: analyseStatusPage.waterForm.taskId,
    // id: 7,
    record_sn: record_sn,
    // record_sn: 49,
  }
  AnalyesAPI.getAnalyseACapacity(josn).then(data => {
    console.log('获取水质容量 A单', data)
    if (!Array.isArray(data) || data.length !== 0) {
      waterForm.value = data
      waterForm.value.bdatas = Array.isArray(data.bdatas) && data.bdatas.length === 0 ? {} : data.bdatas;
      waterForm.value.unit = Array.isArray(data.unit) && data.unit.length === 0 ? {} : data.unit;
      sheetData.value = data.configs
      options.data = sheetData.value
      luckysheet.create(options);
      processedData.value = data.adatas
    } else {
      waterForm.value.device = {
        device_name: [],
        device_model: [],
        device_number: [],
      }
    }
  })
}

const handleAddWaterPh = () => {
  sheetData.value = luckysheet.getLuckysheetfile();
  options.data = sheetData.value; // 将字符串解析为 JSON
  const data = options.data[0].data.map(row => {
    return row
        .map(cell => {
          return cell ? {
            field: cell.m || "默认字段",
            value: cell.v || null
          } : null;
        })
        .filter(cell => cell !== null); // 删除 null 值
  });
  // 调用函数
  processedData.value = filterValidSampleAdatas(processTableData(data));
  cdatas.value = filterValidSamples(transformData(processedData.value))
  if (waterForm.value.check_status !== undefined) {
    delete waterForm.value.check_status
    delete waterForm.value.reviewer_id
  }

//   调接口拿数据
  AnalyesAPI.addWaterCapacity({
    ...waterForm.value,
    record_sn: record_sn,
    // record_sn: 57,
    task_id: analyseStatusPage.waterForm.taskId,
    configs: sheetData.value,
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    adatas: processedData.value,
    cdatas: cdatas.value
  }).then(data => {
    console.log('调接口拿数据', data)
    ElMessage.success('保存成功！')
    switchAdd.value = false
  })
};

const handleSwitch = () => {
  switchAB.value = !switchAB.value
  sheetData.value = luckysheet.getLuckysheetfile();
  options.data = sheetData.value; // 将字符串解析为 JSON
  const data = options.data[0].data.map(row => {
    return row
        .map(cell => {
          return cell ? {
            field: cell.m || "默认字段",
            value: cell.v || null
          } : null;
        })
        .filter(cell => cell !== null); // 删除 null 值
  });
  listB.value.kbyList = kbylSamples(filterValidSampleAdatas(processTableData(data)));
  listB.value.qxyList = qxylSamples(filterValidSampleAdatas(processTableData(data)));
  listB.value.pxyList = filterParallelSamples(filterValidSampleAdatas(processTableData(data)));
  listB.value.bzyList = zkylSamples(filterValidSampleAdatas(processTableData(data)));
  listB.value.jbyList = jbylSamples(filterValidSampleAdatas(processTableData(data)));
  console.log(listB.value)
}

</script>

<template>
  <div class="card">
    <div v-show="switchAB">
      <el-card class="box-card">
        <h1 style="text-align: center">水质 原子荧光光度法分析原始记录（A面）</h1>
        <div>SXLPHJ/JL/CX-22-57</div>
        <table class="table">
          <tr style="background-color: #f2f2f2">
            <td>任务编号</td>
            <td colspan="2">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.task_name"/>
            </td>
            <td>采样日期</td>
            <td>
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.sampling_time"/>
            </td>
            <td>分析日期</td>
            <td colspan="2">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.anal_time"/>
            </td>
          </tr>
          <tr>
            <td>分析项目</td>
            <td colspan="4">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.fxxm"/>
            </td>
            <td>检出限</td>
            <td colspan="2">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.limit_val"/>
            </td>
          </tr>
          <tr style="background-color: #f2f2f2">
            <td>分析方法</td>
            <td colspan="4">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.method"/>
            </td>
            <td>样品类别</td>
            <td colspan="2">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.category_id"/>
            </td>
          </tr>
          <!--          选择仪器组件-->
          <Device :water-form="waterForm" :colspan="2"></Device>
          <tr style="background-color: #f2f2f2">
            <td>环境条件</td>
            <td colspan="2">
              <div>
                <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                          v-model="waterForm.temperature">
                  <template #append>
                    <span style="background-color: transparent;color: black">℃</span>
                  </template>
                </el-input>
                <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                          v-model="waterForm.humidity">
                  <template #append>
                    <span style="background-color: transparent;color: black">%RH</span>
                  </template>
                </el-input>
              </div>
            </td>
            <td>负高压</td>
            <td>
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.fgy">
              </el-input>
            </td>
            <td>灯电流</td>
            <td colspan="2">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.ddl">
              </el-input>
            </td>
          </tr>
          <tr>
            <td>前处理过程</td>
            <td colspan="4">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.process"/>
            </td>
            <td>计算公式</td>
            <td colspan="2">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.js_formula"/>
            </td>
          </tr>
        </table>
        <div id="luckysheet" style="width:100%;height:500px;"></div>
        <table class="table">
          <tr>
            <td style="width: 3%;">备注</td>
            <td colspan="4">
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.notes"/>
            </td>
          </tr>
        </table>
      </el-card>
    </div>
    <div v-show="!switchAB">
      <fluoride-b :waterForm="waterForm" :list-b="listB"></fluoride-b>
    </div>
    <!--    提交校核-->

    <!--    底部公共按钮-->
    <div>
      <Index :water-form="waterForm" :handle-add-water-ph="handleAddWaterPh" :handle-switch="handleSwitch"
             :get-water-capacity="getWaterCapacity" :switch-add="switchAdd" :switch-a-b="switchAB"
             :switch="true"></Index>
    </div>
  </div>

</template>

<style scoped>
.card {
  padding: 20px 25px;
}

.table {
  width: 100%;
  border-collapse: collapse; /* 表格边框合并 */
  text-align: left; /* 默认左对齐 */
  font-size: 14px; /* 字体大小 */
  color: #606266; /* 默认字体颜色 */
}

.table th,
.table td {
  border: 1px solid #c2bfbf; /* 表格单元格边框颜色 */
  padding: 12px; /* 单元格内边距 */
}

.table th {
  background: #f5f7fa; /* 表头背景色 */
  font-weight: 600; /* 表头字体加粗 */
  color: #303133; /* 表头字体颜色 */
  text-align: center; /* 表头居中 */
}

.table td {
  width: 15%;
}

.table-td {
  display: flex;
  justify-content: center;
}


::v-deep .el-input__wrapper {
  background-color: transparent;
  box-shadow: none;
  flex-direction: row-reverse;
}

::v-deep .el-select__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-input-group__append {
  background-color: transparent;
  box-shadow: none;
}
</style>
